import { nextTick } from 'vue'

// 获取阿里字体图标
const getAlicdnIconfont = () => {
  return new Promise((resolve, reject) => {
    nextTick(() => {
      const styles: any = document.styleSheets
      const sheetsList = []
      interface SheetsIconList {
        className: Array<string>
        unicodeName: Array<string>
      }
      const sheetsIconList: SheetsIconList = {
        className: [],
        unicodeName: []
      }
      for (let i = 0; i < styles.length; i++) {
        if (styles[i].href && styles[i].href.indexOf('alifont') > -1) {
          sheetsList.push(styles[i])
        }
      }
      for (let i = 0; i < sheetsList.length; i++) {
        for (let j = 0; j < sheetsList[i].cssRules.length; j++) {
          if (sheetsList[i].cssRules[j].selectorText && sheetsList[i].cssRules[j].selectorText.indexOf('.icon-') > -1) {
            sheetsIconList.className.push(
              `${sheetsList[i].cssRules[j].selectorText
                .substring(1, sheetsList[i].cssRules[j].selectorText.length)
                .replace(/::before/gi, '')}`
            )
            sheetsIconList.unicodeName.push(
              `${sheetsList[i].cssRules[j].cssText.substring(
                sheetsList[i].cssRules[j].cssText.indexOf('content:') + 10,
                sheetsList[i].cssRules[j].cssText.indexOf(';') - 1
              )}`
            )
          }
        }
      }
      if (sheetsIconList.className.length > 0) resolve(sheetsIconList)
      else reject('未获取到值，请刷新重试')
    })
  })
}

/**
 * 获取字体图标 `document.styleSheets`
 * @method ali 获取阿里字体图标 `<i class="iconfont 图标类名"></i>`
 */
const initIconfont = {
  // iconfont
  ali: () => {
    return getAlicdnIconfont()
  }
}

// 导出方法
export default initIconfont
